#define lib_system_c
#define LUA_LIB

extern "C" {
#include "../lua.h"
#include "../lauxlib.h"
#include "../lualib.h"

#include "../lj_def.h" // Included always for the typedefs
#include "../lj_lib.h" // Included always for the typedefs
}

#undef cast
#define GVL_EXCLUDE_STDINT 1 // lj2 has type typedefs

#include "util.hpp"
#include <cmath>
#include <gvl/system/system.hpp>

/* ------------------------------------------------------------------------ */

extern "C" {

#define LJLIB_MODULE_system

LJLIB_CF(system_sleep)
{
	double time = lj_lib_checknum(L, 1);

	uint32_t ms = uint32_t(time * 1000.0);
	gvl::sleep(ms);
	return 0;
}

LJLIB_CF(system_ticks)
{
	uint32_t ticks = gvl::get_ticks();

	setnumV(L->top++, (lua_Number)(int32_t)ticks);
	return 1;
}

LJLIB_CF(system_hires_ticks)
{
	double ticks = gvl::get_hires_ticks() / double(gvl::hires_ticks_per_sec());

	setnumV(L->top++, ticks);
	return 1;
}

#include "../lj_libdef.h"
#include "../lj_lib.h"

LUALIB_API int luaopen_system(lua_State *L)
{
	LJ_LIB_REG(L, system);
	return 1;
}

} // extern "C"
